package com.e3.template.tgf;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.e3.template.model.TGFFormModel;
import com.e3.web.core.model.SuperModel;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.user.client.Element;

public abstract class TGFTabFormPanel<D extends SuperModel> extends TGFFormPanel<D> {
	
	private TabPanel tabPanel;
	
	private Map<TGFFormModel,FormPanel> tabFormMap = new HashMap<TGFFormModel, FormPanel>();
	
	@Override
	protected void onRender(Element parent, int index) {
		super.onRender(parent, index);
		this.setLayout(new FitLayout());
		this.add(getContentPanel());
	}

	protected TabPanel getContentPanel() {
		List<TGFFormModel> formModels = getFormModels();
		if(tabPanel == null){
			Collections.sort(formModels);
			tabPanel = new TabPanel();
			for (TGFFormModel fmodel : formModels) {
				TabItem item = new TabItem(fmodel.getName());
				item.setLayout(new FitLayout());
				FormPanel panel = createSingleFormPanel();
				initFormPanel(panel, fmodel.getFields());
				item.add(panel);
				tabPanel.add(item);
				tabFormMap.put(fmodel, panel);
			}
		}
		return tabPanel;
	}


	public void clearFormData(){
		FormPanel[] panels = new FormPanel[tabFormMap.values().size()];
		tabFormMap.values().toArray(panels);
		for (FormPanel formPanel : panels) {
			formPanel.clear();
		}
	}
	
	public abstract List<TGFFormModel> getFormModels();
	
}
